// 第二步，源数据配置界面
var src_pkColumns = new Array();// 源主表的主键	
$(document).ready(function() {
	// 数据库（主表），下拉树
	bindDbLinkTree("dbLinkId_tree", "dbLinkId_commbox_tree", "dbLinkId", false);

	// 查询表名控件
	$('input[name="searchTableName"]').autocomplete({
        minLength: 0,
        source: webRoot + 'baseconfig/dmsrctable/searchTableNameForSelect.do',
        focus: function (e, ui) {
            $('input[name="searchTableName"]').val(ui.item.tableName);
            return false;
        },
        select: function (e, ui) {
            $('input[name="searchTableName"]').val(ui.item.tableName);
            $('input[name="searchDbLinkId"]').val(ui.item.dbLinkId);
            isEdit = 1;
            return false;
        },
        itemRenderer: function (item) {
            return item.tableName + " -- 数据库实例用户：" + item.dbUserName;
        },
        autoFocus: true
    });

	// 查询按钮点击事件
	$('#button-src-table-search').click(function() {
		var tableName = $('input[name="searchTableName"]').val();
		var dbLinkId = $('input[name="searchDbLinkId"]').val();
		if(dbLinkId == null || dbLinkId == "" || tableName == null || tableName == ""){
			fish.toast('warn', '请选择表名');
			return;
		}
		$.blockUI({message : "数据载入中,请稍候..."});
		$.ajax({
			url : webRoot + 'baseconfig/dmsrctable/searchTableName.do',
			type : 'POST',
			async : true,
			data : {tableName: tableName, dbLinkId: dbLinkId}
		}).done(function(serverData, textStatus, jqXHR) {
			if(serverData.dmSrcTablePO.sourceDataId == -1){
				fish.toast('warn', '该表已经被使用，请选择其他表或者新增表');
				return;
			}
			if(serverData.dmSrcTablePO.allColumns[0].columnName == "-2"){// 没查出表字段
				fish.toast('warn', '表名或者数据库信息变动，未查找出该表字段');
				serverData.dmSrcTablePO.allColumns = null;
			}
			isFirst = true;
			dmStrategyId = serverData.dmStrategyId;
			act = "edit";
			isSearchTable = true;
			// 策略相关的数据回绑
			setStrategyInfo(serverData);
			setRefTableInfo(serverData);
			// 脚本验证字段
			scriptVerifyIsOK = false;
		}).fail(function() {
			fish.toast('error', '网络连接失败！');
		}).always(function() {
			$.unblockUI();
		});
	});
	
	// 新增按钮点击事件
	$('#button-src-table-add').click(function() {
		// 清空第二步的表单信息
		resetSrcTableForm();
	});
	
	// 表名控件
	$('input[name="tableName"]').plancombobox({
		dataTextField : "name",
		dataValueField : "value",
		addMenuWidth:120,
		value:[{type:'table',value:'table_name'}]
	}).on('plancombobox:tablechange',function(e,vals){
		if(vals.newValue.length>50){
			fish.toast('warn', '表名不能超过50个字符');
			tableNameIsOK[0] = false;
		}else{
			tableNameIsOK[0] = true;
		}
		resetRefTableInfo(0);
	});
	
	// 归档类型
	$("input[name=archiveType]").click(function() {
		archiveTypeHideShow();
	});
	
	// 关键字段
	$('select[name="keyColumn"]').multiselect({tabKey:false});
	
	// 源数据表名验证按钮点击事件
	$('#button-src-table-verify').click(function() {
		// 获取表名
		srcTableFormData = $("#srcTableForm").form("value");
		var a = eval(srcTableFormData.tableName);
		var concurrentNumberHidden = true;
		for(var i = 0; i < a.length; i++){
			// 判断是否有分表，用于显示并发数控件
			if(a[i].type == "timer" || a[i].type == "list" || a[i].type == "4"){//4账期 add by lwb
				$('#concurrentNumber').removeClass("hidden");
				concurrentNumberHidden = false;
			}
		}
		if(concurrentNumberHidden){
			$('#concurrentNumber').addClass("hidden");
		}
		// 数据库ID
		if(typeof($('input[name="dbLinkId"]').attr("vId")) == "undefined"){
			fish.toast('warn', '请选择数据库');
			return;
		}
		srcTableFormData.dbLinkId = $('input[name="dbLinkId"]').attr("vId");
		srcTableFormData.dbUserName = $('input[name="dbLinkId"]').val();
		srcTableFormData.keyColumn = null;
		srcTableFormData.dmPlanId = dmPlanId;
		srcTableFormData.isEdit = isEdit;
		// 传到后台，验证表是否存在
		$.blockUI({message : "数据载入中,请稍候..."});
		$.ajax({
			url : webRoot + 'baseconfig/dmsrctable/verifyTableName.do',
			type : 'POST',
			async : true,
			data : srcTableFormData
		}).done(function(serverData, textStatus, jqXHR) {
			if(serverData.success == false){
				fish.toast('warn', serverData.msg);
				return;
			}
			if(serverData.sourceDataId == -1){// 该表已经配置过
				// 清空关键字段
				$('select[name="keyColumn"]').multiselect().multiselect('value', null).multiselect('option',{dataTextField:'value',dataValueField:'id',dataSource:[]});
				fish.toast('warn', '该表已经配置过，且与其他策略相关联，请重新输入表名');
				return;
			}
			if(serverData.sourceDataId == -2){// 该表不存在
				// 清空关键字段
				$('select[name="keyColumn"]').multiselect().multiselect('value', null).multiselect('option',{dataTextField:'value',dataValueField:'id',dataSource:[]});
				fish.toast('warn', '该表不存在，请重新输入表名');
				return;
			}
			if(serverData.sourceDataId == -3){// 已经配置过，但没有和策略关联，没有计划在使用
				// 清空关键字段
				$('select[name="keyColumn"]').multiselect().multiselect('value', null).multiselect('option',{dataTextField:'value',dataValueField:'id',dataSource:[]});
				fish.toast('warn', '该表已经配置过，但未与策略相关联，可通过上面的表名查询快速获取该表的配置信息');
				return;
			}
			// 数据格式：[{columnName: "dm_plan_id", value: "dm_plan_id"},{columnName: "SEQ_NBR", value: "SEQ_NBR"}]
			var pkColumnss = serverData.pkColumns.split(",");
			for (var i = 0; i < pkColumnss.length; i++) {
				src_pkColumns.push(pkColumnss[i]);
			}
			$('select[name="keyColumn"]').multiselect({
				dataTextField: 'columnName',
				dataValueField: 'value',
				dataSource: serverData.allColumns,
				tabKey:false
			}).multiselect("value",src_pkColumns);// 主键默认选中

			// 表索引
			if(serverData.diiPOList.length == 0){
				fish.toast('warn', '该表没有建立索引，建议建立索引');
			}
			// 保存源表索引
			diiPOList_src = serverData.diiPOList;

			// 锁模式
			if(act != "add" && serverData.dbType == 'informix'){
				// 锁模式有变化
				if(serverData.lockMode != $('input[name="lockMode"]').val()){
					fish.toast('warn', '该表锁模式发生变化，请检查确认该变化无误');

				}
			}
			// 向页面放置锁模式
			$('input[name="lockMode"]').val(serverData.lockMode);
//			return;
		}).fail(function() {
			fish.toast('error', '网络连接失败！');
		}).always(function() {
			$.unblockUI();
		});
	});
	
	// 添加从表 按钮事件
	$('#src_add_sub_table').click(function() {
		targetColMaps.push(false);
		var subTables = {sourceDataId : 0, subTableNames : [{type:'table',value:'table_name'}]};
		return newSubTable(subTables);
	});
});

//清空第二步的表单信息
function resetSrcTableForm(){
	$('input[name="tableName"]').plancombobox('reset');
	$('input[name="sourceDataId"]').val("");
	$('input[name="lockMode"]').val("");
	$('input[name="dbLinkId"]').val("");
	$('select[name="keyColumn"]').multiselect().multiselect('value', []).multiselect('option',{dataTextField:'value',dataValueField:'id',dataSource:[]});
	$('#concurrentNumber').addClass("hidden").val(1);
	$($('input[name="hotDataFlag"]')[0]).prop('checked',true);
	$($('input[name="archiveType"]')[0]).prop('checked',true);
	isFirst = true;
	archiveTypeHideShow();
	$('input[name="batchCommitCount"]').val(1000);
	$('input[name="upperCnt"]').val(10);
	// 表名的清空还未完成:$('input[name="tableName"]').clean();
	// 先清空原来的从表
	$("#sub_table tbody").empty();
//	var subTable = document.getElementById("sub_table"); 
//	var rowNum = subTable.rows.length; 
//	for(var i = 0; i < rowNum; i++){ 
//		subTable.deleteRow(i); 
//		rowNum = rowNum - 1; 
//		i = i - 1; 
//	}
	for(var i = 0; i <= seqTable; i++){
		$('#subTableDbLinkId_commbox_tree_' + i).remove();
	}
	var subTables = {sourceDataId : 0, subTableNames : [{type:'table',value:'table_name'}]};
	newSubTable(subTables);
	columnsRelationsIsOK = [];
	columnsRelationsIsOK.push(0);
	targetColMaps = [];
	targetColMaps.push(false);

	// 清空相关的数据
	dmStrategyPO = {};
	dmTargetTablePOList = [];
}
// 是不是第一次选中单表归档
var isFirst = true;
// 归档类型的联动
function archiveTypeHideShow(){
	switch ($("input[name=archiveType]:checked").attr("value")) {
	case "0":// 单表
		if(!isFirst){
			fish.confirm("改为单表归档，配置完成的从表将被清空，确定改为单表归档?").result.then(function(){
				$("#relationFieldGrid").addClass("hidden");
				diiPOList_sub = [];
				for(var i = 1; i < targetColMaps.length; i++){
					delete targetColMaps[i];
					delete columnsRelationsIsOK[i];
					delete tableNameIsOK[i];
					$('#targetTable tr:eq(1)').remove();
					// 把从表设置成删除状态:往删除数据中加源表ID
					var hasID = false;
					for(var j = 1; j <= seqTable; j++){
						if($('input[name="' + subTableId_name + j + '"]').val() != undefined){
							for(var k in delSubTableIds){
								if(delSubTableIds[k] == $('input[name="' + subTableId_name + j + '"]').val()){
									hasID = true;
									break;
								}
							}
							if(!hasID){
								delSubTableIds.push($('input[name="' + subTableId_name + j + '"]').val());
							}
							hasID = false;
						}
					}
				}
				tableNum = 1;
				subTableIsOK = true;
				// 先清空原来的从表
				$("#sub_table tbody").empty(); 
//				var subTable = document.getElementById("sub_table");
//				var rowNum = subTable.rows.length;
//				for(var i = 0; i < rowNum; i++){ 
//					subTable.deleteRow(i); 
//					rowNum = rowNum - 1; 
//					i = i - 1; 
//				}
				for(var i = 0; i <= seqTable; i++){
					$('#subTableDbLinkId_commbox_tree_' + i).remove();
				}
			},function(){
				$($('input[name="archiveType"]')[1]).prop('checked',true);
			});
		}else{
			$("#relationFieldGrid").addClass("hidden");
		}
		break;
	case "1":// 关联
		isFirst = false;
		var subTable = document.getElementById("sub_table");
		var rowNum = subTable.rows.length;
		if(rowNum != 1){
			var subTables = {sourceDataId : 0, subTableNames : [{type:'table',value:'table_name'}]};
			newSubTable(subTables);
		}
		$("#relationFieldGrid").removeClass("hidden");
		//add 默认随主表数据库
		relaDBTree();
		targetColMaps[1]=false
		subTableVerity(1);
		columnsRelationsIsOK[1] = 2;
		break;
	default:
		break;
	}
}
/**
 * 默认主从数据库一致
 * 关联树
 */
function relaDBTree() {
	//begin
	var $dbLinkId = $('input[name="dbLinkId"]');
	if ($dbLinkId.val() != "") {		
		$('input[name="' + subTableDbLinkId_id + seqTable + '"]').val($dbLinkId.val());
		$('input[name="' + subTableDbLinkId_id + seqTable + '"]').attr("vId",$dbLinkId.attr("vId"));
		var treeObj = $.fn.zTree.getZTreeObj(dbLinkIdTree_id + seqTable);
		var parentNode = treeObj.getNodeByParam("id", $dbLinkId.attr("vId"), null);
		var node = treeObj.getNodeByParam("name", $dbLinkId.val(), parentNode);
		treeObj.selectNode(node, false);
	}
	//end
}
//从表配置界面
function subTableVerity(seqTable, tableNames){
	// 数据库（从表），下拉树
	bindDbLinkTree(dbLinkIdTree_id + seqTable, dbLinkIdCommboxTree_id + seqTable, subTableDbLinkId_id + seqTable, false);
	// 去除主从表字段关系默认显示
	// if(act == "edit" || act == "draft"){
	if(act == "edit"){
		$('#' + columnsRelation_id + seqTable + '').empty();
	}
	// 表名控件
	$('input[name="' + subTableName_name + seqTable + '"]').plancombobox({
		dataTextField : "name",
		dataValueField : "value",
		addMenuWidth:120,
		value: tableNames || [{type:'table',value:'table_name'}],
		addMenuSource:[{
            name:'固定变量',
            type:'val'
        },{
            name:'可变参数',
            type:'variable',
            panel:{
                url: webRoot+'/planmanage/addplan/jsp/variablePanel.tpl',
                render: function($extrMenu,source){
                	var tableName = $('input[name="tableName"]').val();
                	var dbLinkId = $('input[name="dbLinkId"]').attr("vId");
                	var dbUserName = $('input[name="dbLinkId"]').val();
                	$.blockUI({message : "数据载入中,请稍候..."});
                	$.ajax({
            			url : webRoot + 'baseconfig/dmsrctable/verifyTableName.do',
            			type : 'POST',
            			async : true,
            			data : {tableName: tableName, dbLinkId: dbLinkId, dbUserName: dbUserName, isEdit: isEdit}
            		}).done(function(serverData, textStatus, jqXHR) {
	                	// 解析，参考主表字段，转换方法
            			if(act == "edit"){// 编辑
            				var subRefCol, variableValue;
            				for(var j = 0; j < tableNames.length; j++){
            					if(tableNames[j].type == "variable"){
            						subRefCol = tableNames[j].subRefCol;
            						variableValue = tableNames[j].variableValue;
            					}
            				}
            			}
	                	$extrMenu.find('input[name="subRefCol"]').combobox({
	                		dataTextField : "columnName",
	                		dataValueField : "value",
	                		value: subRefCol,
	                		dataSource : serverData.allColumns
	                	});
	                	$extrMenu.find('input[name="subDefineValue"]').combobox({
	                		placeholder : "主表字段原值",
	                		dataTextField : "name",
	                		dataValueField : "value",
	                		value : variableValue || 0,
	                		dataSource : [ {
	                			name : "主表字段原值",
	                			value : 0
	                		}, {
	                			name : "年月",
	                			value : 2
	                		}, {
	                			name : "年月日",
	                			value : 3
	                		}, {
	                			name : "账期",
	                			value : 4
	                		}]
	                	});	
            		}).fail(function() {
            			fish.toast('error', '网络连接失败！');
            		}).always(function() {
            			$.unblockUI();
            		});
                },
                value:function($btn,value){
                	var $panel = $btn.data('extrMenu');
                    var subRefCol = $panel.find('input[name=subRefCol]').val();
                    var subDefineValue = $panel.find('input[name=subDefineValue]').val();
                    return subRefCol + ',' + subDefineValue;
                }
            }
        }]
	}).on('plancombobox:tablechange',function(e,vals){
		if(vals.newValue.length > 50){
			fish.toast('warn', '表名不能超过50个字符');
			tableNameIsOK[$('.table-plancombo').index($(this))+1] = false;
		}else{
			tableNameIsOK[$('.table-plancombo').index($(this))+1] = true;
		}
		resetRefTableInfo($('.table-plancombo').index($(this))+1);
	})
	// 从表名验证按钮点击事件
	$('button[name="' + sub_table_verify_button + seqTable + '"]').click(function() {
		srcTableFormData = $("#srcTableForm").form("value");
		var subTableName = $('input[name=' + subTableName_name + seqTable + ']').val();
		var subDbLinkId = $("input[name=subTableDbLinkId_" + seqTable + "]").attr("vId");
		var subDbUserName = $("input[name=subTableDbLinkId_" + seqTable + "]").val();
		var a = eval(srcTableFormData.tableName);
		var concurrentNumberHidden = true;
		for(var i = 0; i < a.length; i++){
			// 判断是否有分表，用于显示并发数控件
			if(a[i].type == "timer" || a[i].type == "list"){
				$('#concurrentNumber').removeClass("hidden");
				concurrentNumberHidden = false;
			}
		}
		if(concurrentNumberHidden){
			$('#concurrentNumber').addClass("hidden");
		}
		// 数据库ID
		srcTableFormData.dbLinkId = $('input[name="dbLinkId"]').attr("vId");
		srcTableFormData.dbUserName = $('input[name="dbLinkId"]').val();
		srcTableFormData.keyColumn = null;
		srcTableFormData.subDbLinkId = subDbLinkId;
		srcTableFormData.subDbUserName = subDbUserName;
		srcTableFormData.subTableName = subTableName;
		var pkColumnss = $('select[name="keyColumn"]').multiselect().val();
		if(typeof(srcTableFormData.dbLinkId) == "undefined" || srcTableFormData.dbLinkId == "" || srcTableFormData.dbLinkId == null
			|| typeof(srcTableFormData.dbUserName) == "undefined" || srcTableFormData.dbUserName == "" || srcTableFormData.dbUserName == null
			|| typeof(srcTableFormData.tableName) == "undefined" || srcTableFormData.tableName == "" || srcTableFormData.tableName == null
			|| typeof(pkColumnss) == "undefined" || pkColumnss == "" || pkColumnss == null){
			fish.toast('warn', '请将主表信息填写完整');
			return;
		}
		$.blockUI({message : "数据载入中,请稍候..."});
		$.ajax({
			url : webRoot + 'baseconfig/dmsrctable/verifySubTableName.do',
			type : 'POST',
			async : true,
			data : srcTableFormData
		}).done(function(serverData, textStatus, jqXHR) {
			if(serverData.sourceDataId == -1){// 表已经存在
				fish.toast('warn', '该表已经配置过，请重新输入表名');
				return;
			}
			if(serverData.sourceDataId == -2){
				fish.toast('warn', '该表不存在，请重新输入表名');
				return;
			}
			$('#' + columnsRelation_id + seqTable + '').empty();
			// 新增主表与从表字段对应关系
			var pkColumns_s = serverData.pkColumns.split(",");
			for (var i = 0; i < pkColumns_s.length; i++) {
				src_pkColumns.push(pkColumns_s[i]);
			}
			var isPK = false;
			for (var i = 0; i < pkColumnss.length; i++) {
				// 判断是不是主表的主键，如果是，则不让删除主从表对应关系
				if(src_pkColumns.indexOf(pkColumnss[i]) >= 0){// 是
					isPK = true;
				}else{
					isPK = false;
				}
				$('#' + columnsRelation_id + seqTable + '').append(newColumnsRelationTr(pkColumnss[i], seqTable, seqRelation, isPK));
				// 从表字段下拉框
				$('input[name="' + subTableColumns_name + seqTable + '_' + seqRelation + '"]').combobox({
					dataTextField:"columnName",
					dataValueField:"value",
					value: pkColumnss[i],
					dataSource: serverData.subAllColumns
				});
				seqRelation++;
			}

			// 表索引
			if(serverData.diiPOList.length == 0){
				fish.toast('warn', '该表没有建立索引，建议建立索引');
			}
			// 保存从表索引
			// 从表还有问题。。。。。。。。。。。。。
			if(act == "add"){
				diiPOList_sub.push(serverData.diiPOList);
			} else {
				var diiPOList_sub_i = 0;
				// 确定从表表索引的第一个游标
				for(var k = 0; k < diiPOList_sub.length; k++){
					if(diiPOList_sub[k] == undefined){
						diiPOList_sub_i++;
					}
				}
				var length_for = diiPOList_sub.length;
				for(var k = diiPOList_sub_i; k < length_for; k++){
					// 各个从表的表索引
					var diiPOList = diiPOList_sub[k];
					// 表一样，替换
					if(diiPOList[0].tableName == serverData.diiPOList[0].tableName){
						delete diiPOList_sub[k];
						diiPOList_sub.push(serverData.diiPOList);
						break;
					}
				}
			}

			// 锁模式
			if(act != "add" && serverData.dbType == 'informix'){
				// 锁模式有变化
				if(serverData.lockMode != $('input[name="lockMode_'+seqTable+'"]').val()){
					fish.toast('warn', '该表锁模式发生变化，请检查确认该变化无误');

				}
			}
			// 向页面放置锁模式
			$('input[name="lockMode_'+seqTable+'"]').val(serverData.lockMode);
			return;
		}).fail(function() {
			fish.toast('error', '网络连接失败！');
		}).always(function() {
			$.unblockUI();
		});
	});
};

//添加从表
var seqTable = 1;
var seqRelation = 1;
var subTableTr_id = "sub_table_";
var subTableDbLinkId_id = "subTableDbLinkId_";
var subTableId_name = "sub_table_Id_";
var subTableName_name = "sub_table_name_";
var columnsRelation_id = "columns_relation_";
var subTableColumns_name = "sub_table_columns_";
var pkColumns_name = "pkColumns_";
var sub_table_verify_button = "button_sub_table_verify_";
var dbLinkIdCommboxTree_id = "subTableDbLinkId_commbox_tree_";
var dbLinkIdTree_id = "subTableDbLinkId_tree_";
//subTableNames：从表表名
function newSubTable(subTables){
	var sourceDataId = subTables.sourceDataId || 0;
	var lockMode = subTables.lockMode || "";
	var subTableNames = subTables.subTableNames || [{type:'table',value:'table_name'}];
	seqTable++;
	var $tr = "";
	$tr += "<tr id='" + subTableTr_id + seqTable + "' class='jqgrow'>";
	$tr += "<td style='width:46%'>";
	$tr += "<div class='form-horizontal'>";
	$tr += "<div class='subrow'>";
	$tr += "<label class='control-label col-sm-2'>数据库</label>";
	$tr += "<div class='col-sm-7'><input type='text' data-rule='required;' data-msg-required='数据库不能为空' readOnly='true' name='" + subTableDbLinkId_id + seqTable + "' class='form-control database-treecombo' /></div>";
	$tr += "</div>";
	$tr += "<div class='subrow hidden'><label class='control-label col-sm-2'>源表分表标识</label>";
	$tr += "<div class='col-sm-8'><input type='text' class='form-control' value='" + sourceDataId + "' name='" + subTableId_name + seqTable + "'/></div>";
	$tr += "</div>";
	$tr += "<div class='form-group hidden'><label class='control-label col-xs-1'>源表锁模式</label>";
	$tr += "<div class='row col-xs-5'><input type='text' value='" + lockMode + "' name='lockMode_"+seqTable+"' /></div>";
	$tr += "</div>";
	$tr += "<div class='subrow'><label class='control-label col-sm-2'>表名</label>";
	$tr += "<div class='col-sm-8'><input type='text' class='form-control table-plancombo' name='" + subTableName_name + seqTable + "'/></div>";
	$tr += "<button type='button' class='btn btn-primary' name='" + sub_table_verify_button + seqTable + "'>验证</button>";
	$tr += "</div>";
	$tr += "</div>";
	$tr += "</td>";
	$tr += "<td style='width:46%'>";
	$tr += "<div class='ui-jqgrid subGrid'>";
	$tr += "<div class='ui-jqgrid-view'>";
	$tr += "<div class='ui-jqgrid-hdiv'>";
	$tr += "<table class='ui-jqgrid-htable' cellspacing='0' cellpadding='0' border='0' style='width:100%'>";
	$tr += "<tr>";
	$tr += "<th style='width:46%' class='ui-th-column'>主表字段</th>";
	$tr += "<th style='width:46%' class='ui-th-column'>从表字段</th>";
	$tr += "<th style='width:8%' class='ui-th-column'>操作</th>";
	$tr += "</tr>";
	$tr += "</table>";
	$tr += "</div>";
	$tr += "<div class='ui-jqgrid-bdiv'>";
	$tr += "<table class='ui-jqgrid-btable' id='" + columnsRelation_id + seqTable + "' cellspacing='0' cellpadding='0' border='0' style='width:100%'>";
	$tr += "<tr><td style='background:#f0f0f0;color:#bbb;text-shadow:1px 1px 0px #fff;text-align: center'>暂无关联字段</td></tr>";
	$tr += "</table>";
	$tr += "</div>";
	$tr += "</div>";
	$tr += "</div>";
	$tr += "</td>";
	$tr += "<td style='width:8%;text-align:center' onClick='getDel(this)'><a href='#' class='glyphicon glyphicon-trash'></a></td>";
	$tr += "</tr>";
	$("#sub_table").append($tr);
	// 数据库（从表），下拉树
	var $dbLinkIdTree = "";
	$dbLinkIdTree += "<div id='" + dbLinkIdCommboxTree_id + seqTable + "' class='dropdown-list' style='position:absolute;display:none'>";
	$dbLinkIdTree += "<div id='" + dbLinkIdTree_id + seqTable + "' class='ztree'></div>";
	$dbLinkIdTree += "</div>";
	$(document.body).append($dbLinkIdTree);
	subTableVerity(seqTable, subTableNames);
	relaDBTree();
	return seqTable;
};

//创建主表与从表字段对应关系tr
// keyColumns：主表字段, seqTable：从表序号, seqRelation：主从表字段对应序号
function newColumnsRelationTr(keyColumns, seqTable, seqRelation, isPK){
	var $tr = "";
	$tr += "<tr class='jqgrow'>";
	$tr += "<td style='width:46%;text-align:center'>";
	$tr += "<input type='text' disabled='true' value='" + keyColumns + "' name='" + pkColumns_name + seqTable + "_" + seqRelation + "' class='form-control'>";
	$tr += "</td>";
	$tr += "<td style='width:46%;text-align:center'>";
	$tr += "<input type='text' data-rule='required;' data-msg-required='从表对应字段不能为空' name='" + subTableColumns_name + seqTable + "_" + seqRelation + "' autocomplete='off' class='form-control'>";
	$tr += "</td>";
	if(isPK){
		$tr += "<td style='width:8%;text-align:center' onClick='getDel(this, 1)'><a href='#' class='glyphicon glyphicon-trash'></a></td>";
	}else{
		$tr += "<td style='width:8%;text-align:center' onClick='getDel(this, 0)'><a href='#' class='glyphicon glyphicon-trash'></a></td>";
	}
	$tr += "</tr>";
	return $tr;
};

//源表信息的数据回绑
function setSrcTableInfo(dmSrcTablePO){
	// 源数据配置界面
	// 保存源表索引
	diiPOList_src = dmSrcTablePO.diiPOList;

	$('input[name="sourceDataId"]').val(dmSrcTablePO.sourceDataId);
	$('input[name="lockMode"]').val(dmSrcTablePO.lockMode);
	$('input[name="dbLinkId"]').val(dmSrcTablePO.dbUserName);
	$('input[name="dbLinkId"]').attr("vId",dmSrcTablePO.dbLinkId);
	var treeObj = $.fn.zTree.getZTreeObj("dbLinkId_tree");
	var parentNode = treeObj.getNodeByParam("id", dmSrcTablePO.dbLinkId, null);
	var node = treeObj.getNodeByParam("name", dmSrcTablePO.dbUserName, parentNode);
	treeObj.selectNode(node, false);
	$('input[name="batchCommitCount"]').val(dmSrcTablePO.batchCommitCount==null ? $('input[name="batchCommitCount"]').attr("value") : dmSrcTablePO.batchCommitCount);
	$('input[name="upperCnt"]').val(dmSrcTablePO.upperCnt==null ? $('input[name="upperCnt"]').attr("value") : dmSrcTablePO.upperCnt);
	if(dmSrcTablePO.hotDataFlag == 0){
		$($('input[name="hotDataFlag"]')[1]).prop('checked',true);
	}else{
		$($('input[name="hotDataFlag"]')[0]).prop('checked',true);
	}
	if(dmSrcTablePO.archiveType == 0){
		// 单表归档
		$($('input[name="archiveType"]')[0]).prop('checked',true);
	}else{
		$($('input[name="archiveType"]')[1]).prop('checked',true);
	}
	// 判断是否有分表，用于显示并发数控件
	var a = dmSrcTablePO.tableNameArray;
	var concurrentNumberHidden = true;
	for(var i = 0; i < a.length; i++){
		if(a[i].type == "timer" || a[i].type == "list"){
			$('#concurrentNumber').removeClass("hidden");
			$('input[name="concurrentNumber"]').val(dmSrcTablePO.concurrentNumber);
			concurrentNumberHidden = false;
		}
	}
	if(concurrentNumberHidden){
		$('#concurrentNumber').addClass("hidden");
	}
	archiveTypeHideShow();
	// 关键字段
	var keyColumnData = new Array();
	if(dmSrcTablePO.keyColumn != null){
		var keyColumns = dmSrcTablePO.keyColumn.split(",");
		for (var i = 0; i < keyColumns.length; i++) {
			keyColumnData.push(keyColumns[i]);
		}
		$('select[name="keyColumn"]').multiselect({
			dataTextField: 'columnName',
			dataValueField: 'value',
			dataSource: dmSrcTablePO.allColumns,
			tabKey:false
		}).multiselect("value",keyColumnData);//自动带出关键主键值
	}
	// 源数据表名控件
	$('input[name="tableName"]').plancombobox({
		dataTextField: "name",
		dataValueField: "value",
		addMenuWidth: 120,
		value: dmSrcTablePO.tableNameArray,
		afterrender:function($extrMenu,source){
			for(var i = 0; i < dmSrcTablePO.tableNameArray.length; i++){
				// 时间变量
				if(dmSrcTablePO.tableNameArray[i].type == "timer"){
					if(dmSrcTablePO.tableNameArray[i].timerValue == "3"){
						$($extrMenu.find('input[name="date_format"]')[0]).prop('checked',true);
					}else if(dmSrcTablePO.tableNameArray[i].timerValue == "2"){
						$($extrMenu.find('input[name="date_format"]')[1]).prop('checked',true);
					}
					$extrMenu.find('input[name="cycleDayxStart"]').val(dmSrcTablePO.tableNameArray[i].upperOffset);
					$extrMenu.find('input[name="cycleDayxEnd"]').val(dmSrcTablePO.tableNameArray[i].lowerOffset);
				}
				// 账期
				if(dmSrcTablePO.tableNameArray[i].type == "4"){
					$extrMenu.find('input[name="startRange"]').val(dmSrcTablePO.tableNameArray[i].upperOffset);
					$extrMenu.find('input[name="endRange"]').val(dmSrcTablePO.tableNameArray[i].lowerOffset);
				}
			}
		}
	});
	// 配置从表数据
	if(dmSrcTablePO.archiveType == 1){
		// 先清空原来的从表
		$("#sub_table tbody").empty();
		for(var i = 0; i <= seqTable; i++){
			$('#subTableDbLinkId_commbox_tree_' + i).remove();
		}
		// 配置新的从表
		for(var i = 0; i < dmSrcTablePO.subTables.length; i++){
			// 从表表索引
			diiPOList_sub.push(dmSrcTablePO.subTables[i].diiPOList);
			// 从表表名控件
			newSubTable(dmSrcTablePO.subTables[i]);
			// 数据库下拉树
			$('input[name="' + subTableDbLinkId_id + seqTable + '"]').attr("vId",dmSrcTablePO.subTables[i].dbLinkId);
			$('input[name="' + subTableDbLinkId_id + seqTable + '"]').val(dmSrcTablePO.subTables[i].subDbUserName);
			var treeObj = $.fn.zTree.getZTreeObj(dbLinkIdTree_id + seqTable);
			var parentNode = treeObj.getNodeByParam("id", dmSrcTablePO.subTables[i].dbLinkId, null);
			var node = treeObj.getNodeByParam("name", dmSrcTablePO.subTables[i].subDbUserName, parentNode);
			treeObj.selectNode(node, false);
			// 字段关系
			var relMapCols = dmSrcTablePO.subTables[i].relMapCols.split(",");
			var subMapCols = dmSrcTablePO.subTables[i].subMapCols.split(",");
			var pkColumnss = dmSrcTablePO.keyColumn.split(",");
			for (var k = 0; k < pkColumnss.length; k++) {
				src_pkColumns.push(pkColumnss[k]);
			}
			var isPK = false;
			for(var j = 0; j < relMapCols.length; j++){
				// 判断是不是主表的主键，如果是，则不让删除主从表对应关系
				if(src_pkColumns.indexOf(relMapCols[j]) >= 0){// 是
					isPK = true;
				}else{
					isPK = false;
				}
				$('#' + columnsRelation_id + seqTable + '').append(newColumnsRelationTr(relMapCols[j], seqTable, seqRelation, isPK));
				// 从表字段下拉框
				$('input[name="' + subTableColumns_name + seqTable + '_' + seqRelation + '"]').combobox({
					dataTextField:"columnName",
					dataValueField:"value",
					value: subMapCols[j],
					dataSource: dmSrcTablePO.subTables[i].allColumns
				});
				seqRelation++;
			}
		}
	}
}

// 获取表单数据-源数据信息
// 返回从表对象
function getSrcTableFormData(){
	srcTableFormData = $("#srcTableForm").form("value");
	// 计划ID
	srcTableFormData.dmPlanId = dmPlanId;
	srcTableFormData.dmStrategyId = dmStrategyId;
	// 策略组号
	srcTableFormData.dmStrategyGroupNum = dmStrategyGroupNum;
	srcTableFormData.expDate = planFormData.expDate;
	// 操作用户
	srcTableFormData.staffId = staffId;
	srcTableFormData.dbLinkId = $('input[name="dbLinkId"]').attr("vId");
	srcTableFormData.dbUserName = $('input[name="dbLinkId"]').val();
	// 表索引
	srcTableFormData.diiPOListStr = JSON.stringify(diiPOList_src);
	// 重组关键字段，用","隔开
	if(srcTableFormData.keyColumn != null){
		var keyColumns = srcTableFormData.keyColumn;
		if(typeof(keyColumns) == "string"){
		}else{
			var keyColumn = keyColumns[0];
			for (var i = 1; i < keyColumns.length; i++) {
				keyColumn = keyColumn + "," + keyColumns[i];
			}
			srcTableFormData.keyColumn = keyColumn;
		}
	}
	// 解析从表参数
	var subTableNames, subTableDbLinkIds, pkColumns, subTableColumns;
	var subTables = new Array();
	var subTable;
	var diiPOList_sub_i = 0;
	// 确定从表表索引的第一个游标
	for(var k = 0; k < diiPOList_sub.length; k++){
		if(diiPOList_sub[k] == undefined){
			diiPOList_sub_i++;
		}
	}
	if(srcTableFormData.archiveType == 1){// 关联归档
		for (var i = 1; i <= seqTable; i++) {
			// 拼接一个从表的数据，用于传到后台
			var subTableName = $("input[name=" + subTableName_name + i + "]").val();
			var subTableId = $("input[name=" + subTableId_name + i + "]").val();
			var subTableDbLinkId = $("input[name=" + subTableDbLinkId_id + i + "]").attr("vId");
			var subDbUserName = $("input[name=" + subTableDbLinkId_id + i + "]").val();
			if(typeof(subTableName) != "undefined" && typeof(subTableDbLinkId) != "undefined"){
				for(var j = 0; j <= seqRelation; j++){
					// 拼接一个主从表字段关系
					var pkColumns_0 = $("input[name=" + pkColumns_name + i + "_" + j + "]").val();
					var subTableColumns_0 = $("input[name=" + subTableColumns_name + i + "_" + j + "]").val();
					if(typeof(pkColumns_0) != "undefined" && typeof(subTableColumns_0) != "undefined"){
						// 拼接
						pkColumns = pkColumns + "," + pkColumns_0;
						subTableColumns = subTableColumns + "," + subTableColumns_0;
					}
				}
				// 表索引
				var diiPOListStr = '';
				for(var k = diiPOList_sub_i; k < diiPOList_sub.length; k++){
					if(diiPOList_sub[k][0].tableName == $.parseJSON(subTableName)[0].value){
						diiPOListStr = JSON.stringify(diiPOList_sub[k]);
						break;
					}
				}
				// 拼接
				subTable = {sourceDataId: subTableId, dbLinkId: subTableDbLinkId, subTableName: subTableName, subDbUserName: subDbUserName, relMapCols: pkColumns, subMapCols: subTableColumns, diiPOListStr: diiPOListStr};
				var noUse;
				pkColumns = noUse;
				subTableColumns = noUse;
				subTables.push(subTable);
			}
		}
		for(var k in delSubTableIds){
			if(delSubTableIds[k] != null && delSubTableIds[k] != ""){
				subTable = {sourceDataId: delSubTableIds[k], isDelete: 1};
				subTables.push(subTable);
			}
		}
	}
	// 判断主从表字段关系有没有填写
	subTableIsOKFunc(subTables);
	tableNum = subTables.length + 1;
	// 判断主从表有没有相同的表
	var tables = subTables;
	var table = {subTableName: srcTableFormData.tableName, dbLinkId: srcTableFormData.dbLinkId};
	tables.push(table);
	for(var i = 0; i < tables.length; i++){
		for(var j = i + 1; j < tables.length; j++){
			if(tables[i].isDelete == 1 || tables[j].isDelete == 1){
				continue;
			}
			if(jQuery.parseJSON(tables[i].subTableName)[0].value.toLowerCase() == jQuery.parseJSON(tables[j].subTableName)[0].value.toLowerCase() && 
					tables[i].dbLinkId == tables[j].dbLinkId){
				return false;
			}
		}
	}
	delete subTables[subTables.length - 1];
	var subTablesStr = JSON.stringify(subTables);
	srcTableFormData.subTablesStr = subTablesStr;
	return subTables;
}